import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp/config.dart';
import 'package:flutterapp/models/general_type.dart';
import 'package:flutterapp/page/utils/common_toast.dart';
import 'package:flutterapp/page/utils/scopoed_model_helper.dart';
import 'package:flutterapp/page/utils/store.dart';
import 'package:flutterapp/scoped_model/city.dart';

class SearchBarPage extends StatefulWidget {
  final bool showLoaction; //展示位置按钮
  final Function goBackCallback; //回退按钮函数
  final String inputValue; //搜索框输入值
  final String defaultInputValue; //搜索框默认值
  final Function onCancel; //取消按钮
  final bool showMap; //展示地图按钮
  final Function onSearch; //用户点击搜索框触发
  final ValueChanged<String> onSearchSubmit;

  const SearchBarPage(
      {Key key,
      this.showLoaction,
      this.goBackCallback,
      this.inputValue = '',
      this.defaultInputValue = '请输入搜索词',
      this.onCancel,
      this.showMap,
      this.onSearch,
      this.onSearchSubmit})
      : super(key: key); //用户输入搜索词后,点击

  @override
  _SearchBarPageState createState() => _SearchBarPageState();
}

class _SearchBarPageState extends State<SearchBarPage> {
  String _searchWord = '';
  String citys = '';
  TextEditingController _controller;
  FocusNode _focus;
  //点击清除
  Function _onClean() {
    _focus = FocusNode();
    _controller.clear();
    setState(() {
      _searchWord = '';
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    //初始化inputValue
    _controller = TextEditingController(text: widget.inputValue);

    super.initState();
  }

  //存入到全局................................
  _saveCity(GeneralType city) async {
    if (city == null) return;
    //存全局状态
    ScopedModelHelper.getModel<CityModel>(context).city = city;
    //存Store
    var store = await Store.getInstance();
    // citySting也就是选中你的城市
    var cityString = json.encode(city.name);
    print(cityString);
    print('----------------');
    store.setString(StoreKeys.city, cityString);
  }

  //点击选择的城市
  _changeLocation() async {
    var result = await CityPickers.showCitiesSelector(
      context: context,
      theme: ThemeData(primaryColor: Colors.green),
    );

    String cityName = result?.cityName;
    if (null == cityName) return;

    //如果cityName里面有city.name 就返回true, 否则就返回false
    //orElse 如果没有返回null
    var city = Config.availableCitys
        .firstWhere((city) => cityName.startsWith(city.name), orElse: () {
      CommonToast.showToast('该城市尚未开通');
      return null;
    });

    print(city.id);
    print(city.name);
    if (city == null) return;

    //存入状态
    _saveCity(city);
  }

  // _getCity() async {
  //   var store = await Store.getInstance();
  //   var cityString = await store.getString(StoreKeys.city);
  //   if (null == cityString) return;
  //   var city = GeneralType.fromJson(json.decode(cityString));
  //   ScopedModelHelper.getModel<CityModel>(context).city = city;
  // }

  @override
  Widget build(BuildContext context) {
    //打开页面自动获取当前定位 如果没有当前定位就默认北京..
    try {
      var city = ScopedModelHelper.getModel<CityModel>(context).city;
      if (city.name != null) {
        setState(() {
          citys = city.name;
        });
      } else {
        setState(() {
          citys = Config.ShenZheng;
        });
      }
      print(city.name);
    } catch (e) {}

    return Container(
      child: Row(
        //mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          if (widget.showLoaction)
            Padding(
              padding: EdgeInsets.only(right: 10.0),
              child: GestureDetector(
                //事件r
                onTap: () {
                  _changeLocation();
                },
                child: Row(
                  //从左往右开始
                  children: [
                    Icon(Icons.room, color: Colors.green, size: 16.0),
                    Text(citys.isNotEmpty ? citys : Config.BeiJing,
                        style: TextStyle(
                          color: Colors.black,
                        )),
                  ],
                ),
              ),
            ),
          if (widget.goBackCallback != null || true)
            Padding(
              padding: EdgeInsets.only(right: 10.0),
              child: GestureDetector(
                onTap: widget.goBackCallback,
                child: Icon(Icons.chevron_left, color: Colors.black87),
              ),
            ),
          Expanded(
            child: Container(
              height: 34.0,
              decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(17.0)),
              margin: EdgeInsets.only(
                right: 10.0,
              ),
              child: TextField(
                //取消焦点
                focusNode: _focus,
                //controller: TextEditingController(text: '234234234'),
                //搜索和搜索提交事件
                onTap: () {
                  //点击搜索框的时候主动失去焦点
                  if (null == widget.onSearchSubmit) {
                    //失去焦点事件......正确写法
                    FocusScope.of(context).requestFocus(FocusNode());
                    //错误写法
                    //_focus.unfocus();
                  }
                  if (widget.onSearch() != null) widget.onSearch();
                },
                //用户输入的
                controller: _controller,
                onSubmitted: widget.onSearchSubmit,
                //键盘事件,激活键盘的时候,键盘的确定变为search
                textInputAction: TextInputAction.search,
                style: TextStyle(fontSize: 14.0),
                onChanged: (String value) {
                  setState(() {
                    _searchWord = value;
                  });
                },
                decoration: InputDecoration(
                    hintText: widget.defaultInputValue,
                    hintStyle: TextStyle(
                      color: Colors.grey,
                      fontSize: 14.0,
                    ),
                    contentPadding: EdgeInsets.only(top: 0.0, left: -10.0),
                    suffixIcon: Padding(
                      padding: EdgeInsets.only(top: 2),
                      //给清除搜索框加事件
                      child: GestureDetector(
                        onTap: () {
                          //清除事件
                          _onClean();
                        },
                        child: Icon(Icons.clear,
                            size: 18.0,
                            color: _searchWord == ''
                                ? Colors.grey[200]
                                : Colors.grey),
                      ),
                    ),
                    border: InputBorder.none,
                    icon: Padding(
                      padding: EdgeInsets.only(top: 3.0, left: 8.0),
                      child: Icon(Icons.search, size: 18.0, color: Colors.grey),
                    )),
                textAlign: TextAlign.start,
              ),
            ),
          ),
          if (widget.onCancel != null || true)
            GestureDetector(
              onTap: widget.onCancel,
              child: Padding(
                padding: EdgeInsets.only(right: 10.0),
                child: Padding(
                    padding: EdgeInsets.only(left: 9.0),
                    child: Text(
                      '取消',
                      style: TextStyle(color: Colors.black, fontSize: 16.0),
                    )),
              ),
            ),
          if (widget.showMap)
            Image.network(
              'http://r0utoyzux.hn-bkt.clouddn.com/2dw.png',
              width: 20.0,
            ),
        ],
      ),
    );
  }
}
